<?php

namespace App\Console\Services\Impl;

use alibaba\nacos\listener\Listener;
use alibaba\nacos\Nacos;
use App\Console\Services\NacosSyncService;
use alibaba\nacos\NacosConfig as Config;
use App\Http\Common\curl\CurlUtil;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Facades\Log;
use Swoole\Exception;

class NacosSyncServiceImpl implements NacosSyncService
{

    /**
     * @var string
     */
    public $snapshotPath;

    /**
     * @var string
     */
    public $configFilePath;

    const HOST = '127.0.0.1:8848';

    const ENV = 'dev';

    const DATA_ID = 'laravel7';

    const GROUP = 'DEFAULT_GROUP';

    const TENANT = '';

    public function __construct()
    {
        $this->snapshotPath = base_path() . DIRECTORY_SEPARATOR;
        $this->configFilePath =  base_path() . DIRECTORY_SEPARATOR . '.env';
    }

    /**
     * @param bool $isWatch
     */
    public function checkNacosUpdate(bool $isWatch = false): void
    {
        Config::setSnapshotPath($this->snapshotPath);
        Listener::add(function (string $config) {
            $this->updateConfig($config);
        });
        $nacos = Nacos::init(self::HOST, self::ENV, self::DATA_ID, self::GROUP, self::TENANT);
        if ($isWatch) {
            $nacos->listener(58);
        } else {
            $this->updateConfig($nacos->runOnce());
        }
    }

    /**
     * @param string $configJson
     */
    private function updateConfig(string $configJson): void
    {
        try {
            $config = $this->jsonToPhpConfig($configJson);
            if (empty($config)) {
                throw new \Exception('disallow empty config');
            }
            file_put_contents($this->configFilePath, $config);
        } catch (Exception $exception) {
            Log::warning('更新nacos配置失败: ' . $exception->getMessage(), ['exception' => $exception]);
            throw $exception;
        }
    }

    /**
     * @param string $configJson
     * @return string
     * @throws \Exception
     */
    private function jsonToPhpConfig(string $configJson): string
    {
        return $configJson;
        $phpConfig = json_decode($configJson, true);
        if (json_last_error() != JSON_ERROR_NONE) {
            throw new \Exception('配置解析失败');
        }

        return "<?php \nreturn " . var_export($phpConfig, true) . ';';
    }

    public function publishNaocsConfig(): void
    {
        $url = self::HOST . '/nacos/v1/cs/configs';
        $content = file_get_contents('./.env');
        $params = [
            'tenant' => 'tools',
            'dataId' => 'laravel7',
            'group' => 'dev',
            'content' => $content
        ];
        $params = http_build_query($params);
        $resp = CurlUtil::xpost($url, $params);
        if ($resp) {
            echo "发布配置成功";
        }
    }
}
